import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useElectricalStore = defineStore('electrical', () => {
  // 电路组件
  const components = ref([
    {
      id: 'switch-1',
      type: 'switch',
      name: '开关',
      category: 'control',
      properties: {
        voltage: 220,
        current: 10,
        poles: 1,
        position: 'on' // on, off
      },
      position: { x: 100, y: 100 },
      connections: []
    },
    {
      id: 'outlet-1',
      type: 'outlet',
      name: '插座',
      category: 'distribution',
      properties: {
        voltage: 220,
        current: 16,
        type: 'standard', // standard, usb, ethernet
        grounded: true
      },
      position: { x: 200, y: 100 },
      connections: []
    },
    {
      id: 'light-1',
      type: 'light',
      name: '灯具',
      category: 'load',
      properties: {
        voltage: 220,
        power: 60, // watts
        type: 'led', // led, incandescent, fluorescent
        dimmable: false
      },
      position: { x: 300, y: 100 },
      connections: []
    }
  ])

  // 电路连接
  const connections = ref([
    {
      id: 'conn-1',
      from: 'switch-1',
      to: 'outlet-1',
      type: 'wire',
      properties: {
        gauge: 2.5, // mm²
        material: 'copper',
        insulation: 'pvc',
        color: 'red'
      },
      path: [
        { x: 100, y: 100 },
        { x: 200, y: 100 }
      ]
    }
  ])

  // 电路系统
  const circuits = ref([
    {
      id: 'circuit-1',
      name: '主电路',
      type: 'power',
      properties: {
        voltage: 220,
        maxCurrent: 32,
        breaker: '32A',
        phase: 'single'
      },
      components: ['switch-1', 'outlet-1', 'light-1'],
      connections: ['conn-1']
    }
  ])

  // 电气规范
  const electricalCodes = ref({
    voltage: {
      residential: 220,
      commercial: 380,
      industrial: 660
    },
    wireGauge: {
      '1.5': { maxCurrent: 10, applications: ['lighting'] },
      '2.5': { maxCurrent: 16, applications: ['outlets', 'lighting'] },
      '4.0': { maxCurrent: 25, applications: ['outlets', 'appliances'] },
      '6.0': { maxCurrent: 32, applications: ['appliances', 'heating'] },
      '10.0': { maxCurrent: 40, applications: ['heating', 'air-conditioning'] }
    },
    breakerSizes: [6, 10, 16, 20, 25, 32, 40, 50, 63],
    colorCodes: {
      'live': '#FF0000',
      'neutral': '#0000FF',
      'ground': '#FFFF00',
      'control': '#00FF00'
    }
  })

  // 计算属性
  const totalComponents = computed(() => components.value.length)
  const totalConnections = computed(() => connections.value.length)
  const totalCircuits = computed(() => circuits.value.length)

  const componentsByCategory = computed(() => {
    const grouped = {}
    components.value.forEach(component => {
      if (!grouped[component.category]) {
        grouped[component.category] = []
      }
      grouped[component.category].push(component)
    })
    return grouped
  })

  const componentsByType = computed(() => {
    const grouped = {}
    components.value.forEach(component => {
      if (!grouped[component.type]) {
        grouped[component.type] = []
      }
      grouped[component.type].push(component)
    })
    return grouped
  })

  const totalPower = computed(() => {
    return components.value
      .filter(comp => comp.type === 'light' || comp.type === 'appliance')
      .reduce((total, comp) => total + (comp.properties.power || 0), 0)
  })

  const totalCurrent = computed(() => {
    return components.value
      .filter(comp => comp.type === 'light' || comp.type === 'appliance')
      .reduce((total, comp) => total + (comp.properties.current || 0), 0)
  })

  const circuitLoads = computed(() => {
    return circuits.value.map(circuit => {
      const circuitComponents = components.value.filter(comp => 
        circuit.components.includes(comp.id)
      )
      const load = circuitComponents.reduce((total, comp) => 
        total + (comp.properties.current || 0), 0
      )
      return {
        circuitId: circuit.id,
        circuitName: circuit.name,
        load,
        maxLoad: circuit.properties.maxCurrent,
        percentage: (load / circuit.properties.maxCurrent) * 100
      }
    })
  })

  // Actions
  const addComponent = (componentData) => {
    const newComponent = {
      id: generateId(),
      type: 'component',
      name: '新组件',
      category: 'general',
      properties: {
        voltage: 220,
        current: 0
      },
      position: { x: 0, y: 0 },
      connections: [],
      ...componentData
    }
    
    components.value.push(newComponent)
    return newComponent
  }

  const updateComponent = (componentId, updates) => {
    const index = components.value.findIndex(comp => comp.id === componentId)
    if (index !== -1) {
      components.value[index] = { ...components.value[index], ...updates }
      return components.value[index]
    }
  }

  const deleteComponent = (componentId) => {
    const index = components.value.findIndex(comp => comp.id === componentId)
    if (index !== -1) {
      // 删除相关连接
      connections.value = connections.value.filter(conn => 
        conn.from !== componentId && conn.to !== componentId
      )
      
      // 从电路中移除
      circuits.value.forEach(circuit => {
        circuit.components = circuit.components.filter(id => id !== componentId)
      })
      
      components.value.splice(index, 1)
      return true
    }
    return false
  }

  const moveComponent = (componentId, position) => {
    const component = components.value.find(comp => comp.id === componentId)
    if (component) {
      component.position = position
      updateConnections(componentId)
    }
  }

  const addConnection = (connectionData) => {
    const newConnection = {
      id: generateId(),
      from: '',
      to: '',
      type: 'wire',
      properties: {
        gauge: 2.5,
        material: 'copper',
        insulation: 'pvc',
        color: 'red'
      },
      path: [],
      ...connectionData
    }
    
    connections.value.push(newConnection)
    return newConnection
  }

  const updateConnection = (connectionId, updates) => {
    const index = connections.value.findIndex(conn => conn.id === connectionId)
    if (index !== -1) {
      connections.value[index] = { ...connections.value[index], ...updates }
      return connections.value[index]
    }
  }

  const deleteConnection = (connectionId) => {
    const index = connections.value.findIndex(conn => conn.id === connectionId)
    if (index !== -1) {
      connections.value.splice(index, 1)
      return true
    }
    return false
  }

  const updateConnections = (componentId) => {
    // 更新与指定组件相关的连接路径
    connections.value.forEach(connection => {
      if (connection.from === componentId || connection.to === componentId) {
        const fromComponent = components.value.find(comp => comp.id === connection.from)
        const toComponent = components.value.find(comp => comp.id === connection.to)
        
        if (fromComponent && toComponent) {
          connection.path = calculateConnectionPath(fromComponent.position, toComponent.position)
        }
      }
    })
  }

  const calculateConnectionPath = (from, to) => {
    // 简单的直线连接，可以扩展为更复杂的路径算法
    return [
      { x: from.x, y: from.y },
      { x: to.x, y: to.y }
    ]
  }

  const addCircuit = (circuitData) => {
    const newCircuit = {
      id: generateId(),
      name: '新电路',
      type: 'power',
      properties: {
        voltage: 220,
        maxCurrent: 32,
        breaker: '32A',
        phase: 'single'
      },
      components: [],
      connections: [],
      ...circuitData
    }
    
    circuits.value.push(newCircuit)
    return newCircuit
  }

  const updateCircuit = (circuitId, updates) => {
    const index = circuits.value.findIndex(circuit => circuit.id === circuitId)
    if (index !== -1) {
      circuits.value[index] = { ...circuits.value[index], ...updates }
      return circuits.value[index]
    }
  }

  const deleteCircuit = (circuitId) => {
    const index = circuits.value.findIndex(circuit => circuit.id === circuitId)
    if (index !== -1) {
      circuits.value.splice(index, 1)
      return true
    }
    return false
  }

  const addComponentToCircuit = (circuitId, componentId) => {
    const circuit = circuits.value.find(circuit => circuit.id === circuitId)
    if (circuit && !circuit.components.includes(componentId)) {
      circuit.components.push(componentId)
    }
  }

  const removeComponentFromCircuit = (circuitId, componentId) => {
    const circuit = circuits.value.find(circuit => circuit.id === circuitId)
    if (circuit) {
      circuit.components = circuit.components.filter(id => id !== componentId)
    }
  }

  const validateCircuit = (circuitId) => {
    const circuit = circuits.value.find(circuit => circuit.id === circuitId)
    if (!circuit) return { valid: false, errors: ['电路不存在'] }
    
    const errors = []
    
    // 检查负载
    const circuitComponents = components.value.filter(comp => 
      circuit.components.includes(comp.id)
    )
    const totalLoad = circuitComponents.reduce((total, comp) => 
      total + (comp.properties.current || 0), 0
    )
    
    if (totalLoad > circuit.properties.maxCurrent) {
      errors.push(`电路负载超限: ${totalLoad}A > ${circuit.properties.maxCurrent}A`)
    }
    
    // 检查连接
    const circuitConnections = connections.value.filter(conn => 
      circuit.connections.includes(conn.id)
    )
    
    circuitConnections.forEach(connection => {
      const fromComponent = components.value.find(comp => comp.id === connection.from)
      const toComponent = components.value.find(comp => comp.id === connection.to)
      
      if (!fromComponent || !toComponent) {
        errors.push(`连接 ${connection.id} 引用了不存在的组件`)
      }
    })
    
    return {
      valid: errors.length === 0,
      errors,
      load: totalLoad,
      maxLoad: circuit.properties.maxCurrent
    }
  }

  const validateAllCircuits = () => {
    return circuits.value.map(circuit => ({
      circuitId: circuit.id,
      circuitName: circuit.name,
      ...validateCircuit(circuit.id)
    }))
  }

  const calculateWireGauge = (current) => {
    const wireGauges = Object.keys(electricalCodes.value.wireGauge)
    for (const gauge of wireGauges) {
      if (electricalCodes.value.wireGauge[gauge].maxCurrent >= current) {
        return gauge
      }
    }
    return '10.0' // 默认最大规格
  }

  const suggestBreakerSize = (current) => {
    const breakerSizes = electricalCodes.value.breakerSizes
    for (const size of breakerSizes) {
      if (size >= current) {
        return size
      }
    }
    return 63 // 默认最大规格
  }

  const generateBillOfMaterials = () => {
    const bom = {
      components: {},
      wires: {},
      breakers: {},
      total: {
        components: 0,
        wireLength: 0,
        breakers: 0
      }
    }
    
    // 统计组件
    components.value.forEach(component => {
      const type = component.type
      if (!bom.components[type]) {
        bom.components[type] = { count: 0, items: [] }
      }
      bom.components[type].count++
      bom.components[type].items.push(component)
      bom.total.components++
    })
    
    // 统计电线
    connections.value.forEach(connection => {
      const gauge = connection.properties.gauge
      if (!bom.wires[gauge]) {
        bom.wires[gauge] = { length: 0, count: 0 }
      }
      
      // 计算连接长度
      const length = calculateConnectionLength(connection.path)
      bom.wires[gauge].length += length
      bom.wires[gauge].count++
      bom.total.wireLength += length
    })
    
    // 统计断路器
    circuits.value.forEach(circuit => {
      const breaker = circuit.properties.breaker
      if (!bom.breakers[breaker]) {
        bom.breakers[breaker] = 0
      }
      bom.breakers[breaker]++
      bom.total.breakers++
    })
    
    return bom
  }

  const calculateConnectionLength = (path) => {
    let length = 0
    for (let i = 1; i < path.length; i++) {
      const dx = path[i].x - path[i-1].x
      const dy = path[i].y - path[i-1].y
      length += Math.sqrt(dx * dx + dy * dy)
    }
    return length
  }

  const exportElectricalData = () => {
    return {
      components: components.value,
      connections: connections.value,
      circuits: circuits.value,
      electricalCodes: electricalCodes.value,
      exportTime: Date.now()
    }
  }

  const importElectricalData = (data) => {
    if (data.components && Array.isArray(data.components)) {
      components.value = data.components
    }
    
    if (data.connections && Array.isArray(data.connections)) {
      connections.value = data.connections
    }
    
    if (data.circuits && Array.isArray(data.circuits)) {
      circuits.value = data.circuits
    }
    
    if (data.electricalCodes) {
      electricalCodes.value = { ...electricalCodes.value, ...data.electricalCodes }
    }
  }

  const reset = () => {
    components.value = []
    connections.value = []
    circuits.value = []
  }

  // 辅助函数
  const generateId = () => {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  return {
    // 状态
    components,
    connections,
    circuits,
    electricalCodes,
    
    // 计算属性
    totalComponents,
    totalConnections,
    totalCircuits,
    componentsByCategory,
    componentsByType,
    totalPower,
    totalCurrent,
    circuitLoads,
    
    // Actions
    addComponent,
    updateComponent,
    deleteComponent,
    moveComponent,
    addConnection,
    updateConnection,
    deleteConnection,
    updateConnections,
    calculateConnectionPath,
    addCircuit,
    updateCircuit,
    deleteCircuit,
    addComponentToCircuit,
    removeComponentFromCircuit,
    validateCircuit,
    validateAllCircuits,
    calculateWireGauge,
    suggestBreakerSize,
    generateBillOfMaterials,
    calculateConnectionLength,
    exportElectricalData,
    importElectricalData,
    reset
  }
})
